import { message } from 'ant-design-vue';
import api from '@/api/index.js'
export async function apiGet(url, params = {}, errorMessage = '请求错误') {
  try {
    const response = await api.get(url, params);
    return response; // 返回成功响应
  } catch (error) {
    console.error(errorMessage);
    message.error(errorMessage); // 显示自定义错误消息
    return null;
  }
};

export async function apiPost(url, params = {}, errorMessage = 'An error occurred') {
  try {
    const response = await api.post(url, params);
    return response; // 返回成功响应
  } catch (error) {
    message.error(errorMessage); // 显示自定义错误消息
    return null;
  }
};

export function serializeForm(data) {
  return Object.keys(data)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
    .join('&');
}

// 设置 Cookie 函数
export function setCookie(name, value, days) {
  let expires = "";
  if (days) {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

export function getNestedField(item, field) {
  const fields = field.split('.');
  let current = item;

  for (let i = 0; i < fields.length; i++) {
      if (current[fields[i]] === undefined) {
          return undefined;  // 若嵌套属性不存在，返回 undefined
      }
      current = current[fields[i]];
  }
  return current;
}

export function debounce(func, wait) {
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
}